import { ConfigProvider } from './../../config/config.provider';
import { RedisService } from './../util/redis.service';
import { Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthPayload } from './auth.payload';
import { getRepository } from 'typeorm';
import { AdminUser } from '../admin-user/admin-user.entity';
import { RoleService } from '../role/role.service';

@Injectable()
export class AuthService {

  constructor(private readonly jwtService: JwtService,
              private roleService: RoleService,
              private redisService: RedisService) { }

  signIn(payload: AuthPayload) {
    // In the real-world app you shouldn't expose this method publicly
    // instead, return a token once you verify user credentials
    return this.jwtService.sign(payload, { expiresIn: '7 days' });
  }

  async validateUser(userId: number): Promise<any> {
    const user = await getRepository(AdminUser).findOne(userId);
    if (!user) {
      return null;
    }
    // 从redis获取用户权限
    const key = `${ConfigProvider.getConfig('constant').userPrivKey + userId}`;
    // console.log('key is ', key);
    try {
      let userPriv = await this.redisService.get(key);
      // console.log('userPriv is ', userPriv);
      if (!userPriv) {
        userPriv = (await this.roleService.getPrivilegeList(String(userId))).map(x => x.privCode);
        this.redisService.set(key, JSON.stringify(userPriv));
        return { user, userPriv };
      } else {
        return { user, userPriv: JSON.parse(userPriv) };
      }
    } catch (error) {
      Logger.error(error, '', AuthService.name);
      // console.log('error is ', error);
      return null;
    }
  }
}
